import React, { useEffect, useState} from "react";
import {NavigateFunction} from "react-router-dom";
import { App as AntdApp } from "antd";
import { StyleRegistry } from "styled-jsx";
import css from 'styled-jsx/css';

import ProAppWrapper from 'vendor/components/pro-appWrapper';
import { ProRouter, ProRouterProps } from "vendor/components/pro-router";
import { setRequestConf } from "vendor/utils/T/core/request";
import prompt from "vendor/utils/prompt";

import { InitModalMountPoint } from "vendor/components/pro-hoc/withModal";
import { getAppRoutes, setEnv, getEnv, EnumRouter, EnumEnvType, noValidateLoginRoutes,noValidateMenuPermissions, ThemeConfigProvider, IThemeToken, getThemeTokenList } from "@/constants";
import { checkLogin } from "@/components/app/login/api"
import { permission, EnumAuthKey } from "@/service/permission"

// 日期国际化
import 'dayjs/locale/zh-cn';

// 引入tailwindcss
import "tailwindcss/tailwind.css";

interface AppProps {
    env?: EnumEnvType;
    appRouterProps?: ProRouterProps;
    token: IThemeToken,
}

const App:React.FC<AppProps> = (props) => {
    const { globalStyle, appRouterProps, proAppWrapperProps } = useGlobalConfig(props);
    return <StyleRegistry>
        <AntdApp>
            <ProAppWrapper {...proAppWrapperProps}>
                <ProRouter {...appRouterProps} />
                <InitModalMountPoint />
                {prompt.initMountPoint()}
            </ProAppWrapper>
        </AntdApp>
        <style jsx global>{globalStyle}</style>
    </StyleRegistry>
}

App.defaultProps = {
    // @ts-ignore
    env: window.ENV
};

export default () => {
    const tokenList = getThemeTokenList();
    const [ token, setToken ] = useState(tokenList.navyBlue.token);
    return <ThemeConfigProvider token={token}>
        <App token={token}/>
    </ThemeConfigProvider>;
}

/**
 * 初始化全局配置
 */
const useGlobalConfig = ({ env, appRouterProps, token: themeToken}: AppProps) => {
    const [ loading, setLoading ] = useState(true);

    setEnv(env);    // 设置环境变量

    // 设置request http client的配置
    // @ts-ignore
    setRequestConf({ apiDomain: getEnv().apiDomain, apiResponseCode: getEnv().apiResponseCode, });

    useEffect(() => {
        const currentPathname = trimLSRlash(window.location.pathname);
        if(!noValidateLoginRoutes.map(item => trimLSRlash(item)).includes(currentPathname)) {
            // 用于获取全局的系统配置
            // getSysConfig().then(resp => {
            //     setEnv({sysConfig: resp.data})
            //     setLoading(false);
            // }).catch(() => {
            //     setLoading(false);
            // })

            setLoading(false);
        }else{
            setLoading(false);
        }
    }, []);

    return {
        appRouterProps: Object.assign({
            rootPath: EnumRouter.rootRoute,
            redirectPath: EnumRouter.appRoot,
            mounted: (navigate: NavigateFunction) => {
                // @ts-ignore
                setRequestConf({redirectLogin: () => {
                    navigate(EnumRouter.login, {replace: true})
                    // window.location.href = EnumRouter.login;
                    if (document.querySelector("#sk-mount-modal")) document.querySelector("#sk-mount-modal").remove()
                }})
            },
            appRoutes: getAppRoutes(),
            authorized: {
                // 路由权限
                permissions: validatePermission(),
                noVerifyLoginPathList: noValidateLoginRoutes,
                noLoginRedirectPath: EnumRouter.login,
                checkLogin: asyncCheckLogin,
            }
        },appRouterProps),

        proAppWrapperProps: {
            loading,
            allowBrowser: getEnv().allowBrowser,
            lang: {
                type: "zh",
                intlMessages: {}
            }
        },

        globalStyle: getGlobalStyle(themeToken),
    }
}

// 校验权限
const validatePermission = () => {
    // TODO 暂不校验菜单权限
    return null

    if (permission.isSuperAdmin()) return null;

    return [
        ...noValidateMenuPermissions,
        ...Object.keys(EnumRouter)
            // @ts-ignore
            .filter((router) => permission.can(EnumAuthKey[router]))
            // @ts-ignore
            .map((key) => EnumRouter[key])
    ];
}

// 异步检查登录
const asyncCheckLogin = () => new Promise((resolve, reject) => {
    // const { userId } = permission.loginUser.get();
    // if(!userId) return reject();
    //
    // checkLogin(false).then(() => resolve(true)).catch(() => reject());

    resolve(true);
})

// 清除左右斜线
const trimLSRlash = (str: string) => str.replace(/\/$/, "").replace(/^\//, "");

// 全局样式
const getGlobalStyle = (themeToken: IThemeToken) => {
    // language=SCSS
    return css.global`
      * {
        box-sizing: border-box;
      }
      html {
        height: 100%;
        body {
          height: 100%;
          margin: 0;
          padding: 0;
          color: ${themeToken.colorText};
          background: ${themeToken.custom.bodyBgColor};
          > #wrapper {
            height: 100%;
            & > .ant-app{
              height: 100%;
            }
          }
        }
      }
    `
}
